Functions

If you find yourself doing the same thing over and over again in your code, it might be time to write a function. A function is a bit of reusable code that you can use throughout your script. In Excel, for instance, =SUM() is a function.

Python has a number of built-in functions -- print() is one of them -- but you can also write your own. This can help keep your code tidy.

Typically, a function takes arguments as inputs, does something with the inputs, then returns a value.

For instance, you could write a function that takes a number and returns that number minus 10:


In [ ]:
def minusTen(num):
    return num - 10

Notice a couple things here:

  • Functions start with the keyword def
  • Functions have a name (ours is called "minusTen")
  • If you need to pass one or more arguments to the function, you define them inside parentheses ("num" is just a variable name I made up -- it could be anything)
  • The special Python word "return," which tells the function to return the value to the script

Simply defining a function does nothing -- you have to call the function to use it. Let's save the output of the function to a variable:


In [ ]:
my_number = minusTen(100)
print(my_number)

In this case we're passing the number 100 to the function. The function's job is to subtract 10 from whatever number you give it and return the result. The result is stored in the my_number variable.

What happens if you hand the function something that's not a number? You'd get an error -- an "exception," as they're called in Python.


In [ ]:
minusTen('Ninety')

What happens if you call the function without providing an argument?


In [ ]:
minusTen()

If this were a real function, we'd want to build in some error handling to make sure that the function has in fact received and argument and that it's a number.

You could also set your function up to have a default value for the variable:


In [ ]:
def minusTen(num=100):
    return num - 10

Now, if you call the function without specifying an argument, it will return 90.


In [ ]:
minusTen()